package cn.iocoder.yudao.module.system.dal.mysql.warehouse;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.controller.admin.warehouse.vo.GoldMaterialWarehousePageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.warehouse.GoldMaterialWarehouseDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

@Mapper
public interface GoldMaterialWarehouseMapper extends BaseMapperX<GoldMaterialWarehouseDO> {

    default PageResult<GoldMaterialWarehouseDO> selectPage(GoldMaterialWarehousePageReqVO reqVO) {
        LambdaQueryWrapperX<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                .likeIfPresent(GoldMaterialWarehouseDO::getName, reqVO.getName())
                .eqIfPresent(GoldMaterialWarehouseDO::getStatus, reqVO.getStatus())
                .orderByDesc(GoldMaterialWarehouseDO::getId);

        // 优先使用types数组筛选，如果types为空则使用单个type
        if (reqVO.getTypes() != null && !reqVO.getTypes().isEmpty()) {
            wrapper.in(GoldMaterialWarehouseDO::getType, reqVO.getTypes());
        } else {
            wrapper.eqIfPresent(GoldMaterialWarehouseDO::getType, reqVO.getType());
        }
        
        // 添加团队仓ID查询条件
        wrapper.eqIfPresent(GoldMaterialWarehouseDO::getTeamWarehouseId, reqVO.getTeamWarehouseId());

        // 权限过滤：根据中间表(gold_material_warehouse_user)过滤仓库数据
        // 只查看与自己关联的仓库（通过中间表的user_id过滤）
        if (reqVO.getAllowedWarehouseIds() != null && !reqVO.getAllowedWarehouseIds().isEmpty()) {
            wrapper.in(GoldMaterialWarehouseDO::getId, reqVO.getAllowedWarehouseIds());
        }

        return selectPage(reqVO, wrapper);
    }

    @Select("select * from gold_material_warehouse where id = #{id} for update")
    GoldMaterialWarehouseDO selectByIdForUpdate(@Param("id") Long id);

    @Update("update gold_material_warehouse set balance = balance + #{delta} " +
            "where id = #{id} and (#{delta} >= 0 or balance + #{delta} >= 0)")
    int updateBalanceDelta(@Param("id") Long id, @Param("delta") BigDecimal delta);

    /**
     * 查询调拨仓库选项
     * 查询类型为公司仓(1)和团队仓(2)的仓库，排除指定仓库
     */
    /**
     * 查询调拨仓库选项
     * 查询指定类型的仓库，排除指定仓库
     */
    default List<GoldMaterialWarehouseDO> selectTransferOptions(Long excludeWarehouseId, List<Integer> warehouseTypes) {
        LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                .eq(GoldMaterialWarehouseDO::getStatus, 1) // 只查询启用状态的仓库
                .orderByAsc(GoldMaterialWarehouseDO::getType)
                .orderByAsc(GoldMaterialWarehouseDO::getName);

        // 如果指定了仓库类型，使用指定的类型；否则默认查询公司仓和团队仓
        if (warehouseTypes != null && !warehouseTypes.isEmpty()) {
            wrapper.in(GoldMaterialWarehouseDO::getType, warehouseTypes);
        }

        // 排除指定仓库
        if (excludeWarehouseId != null) {
            wrapper.ne(GoldMaterialWarehouseDO::getId, excludeWarehouseId);
        }

        return selectList(wrapper);
    }

    // 查询总金料余额（所有仓库余额之和）
    @Select("SELECT COALESCE(SUM(balance), 0) FROM gold_material_warehouse WHERE deleted = 0 AND status = 1")
    BigDecimal selectTotalBalance();

    // 查询仓库总数量
    @Select("SELECT COUNT(*) FROM gold_material_warehouse WHERE deleted = 0 AND status = 1")
    Integer selectWarehouseCount();

    /**
     * 查询所有状态为开启的仓库简单信息
     * 只返回id、name、balance字段
     */
    default List<GoldMaterialWarehouseDO> selectEnabledWarehouseSimpleList() {
        LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                .select(GoldMaterialWarehouseDO::getId, GoldMaterialWarehouseDO::getName, GoldMaterialWarehouseDO::getBalance)
                .eq(GoldMaterialWarehouseDO::getStatus, 1) // 只查询启用状态的仓库
                .orderByAsc(GoldMaterialWarehouseDO::getName);
        return selectList(wrapper);
    }

    /**
     * 根据团队仓ID查询所有人员仓库
     */
    default List<GoldMaterialWarehouseDO> selectPersonWarehousesByTeamWarehouseId(Long teamWarehouseId) {
        LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                .eq(GoldMaterialWarehouseDO::getType, 3) // 人员仓
                .eq(GoldMaterialWarehouseDO::getTeamWarehouseId, teamWarehouseId)
                .eq(GoldMaterialWarehouseDO::getStatus, 1) // 启用状态
                .orderByAsc(GoldMaterialWarehouseDO::getName);
        return selectList(wrapper);
    }

    /**
     * 查询团队仓下的人员仓库数量
     */
    default Long selectPersonWarehouseCountByTeamWarehouseId(Long teamWarehouseId) {
        LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                .eq(GoldMaterialWarehouseDO::getType, 3) // 人员仓
                .eq(GoldMaterialWarehouseDO::getTeamWarehouseId, teamWarehouseId)
                .eq(GoldMaterialWarehouseDO::getStatus, 1); // 启用状态
        return selectCount(wrapper);
    }

    /**
     * 查询所有团队仓
     */
    default List<GoldMaterialWarehouseDO> selectAllTeamWarehouses() {
        LoginUser loginUser = getLoginUser();
        Long id = loginUser.getId();
        LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GoldMaterialWarehouseDO::getUserId,id);
        wrapper.eq(GoldMaterialWarehouseDO::getStatus, 1);
        wrapper.eq(GoldMaterialWarehouseDO::getType, 2);
        return selectList(wrapper);
    }

    /**
     * 根据团队仓ID查询相同ID的仓库
     */
    default List<GoldMaterialWarehouseDO> selectWarehousesByTeamWarehouseId(Long teamWarehouseId) {
        LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                .eq(GoldMaterialWarehouseDO::getId, teamWarehouseId)
                .eq(GoldMaterialWarehouseDO::getStatus, 1) // 启用状态
                .orderByAsc(GoldMaterialWarehouseDO::getName);
        return selectList(wrapper);
    }

    default List<GoldMaterialWarehouseDO> getWarehousesByTeamWarehouseIds(Long teamWarehouseId){
        GoldMaterialWarehouseDO goldMaterialWarehouseDO = selectById(teamWarehouseId);
        if (goldMaterialWarehouseDO.getType()==2){
            LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                    .eq(GoldMaterialWarehouseDO::getTeamWarehouseId, teamWarehouseId)
                    .eq(GoldMaterialWarehouseDO::getStatus, 1) // 启用状态
                    .orderByAsc(GoldMaterialWarehouseDO::getId);
            return selectList(wrapper);
        }else if(goldMaterialWarehouseDO.getType()==1){
            LambdaQueryWrapper<GoldMaterialWarehouseDO> wrapper = new LambdaQueryWrapperX<GoldMaterialWarehouseDO>()
                    //.eq(GoldMaterialWarehouseDO::getTeamWarehouseId, teamWarehouseId)
                    .eq(GoldMaterialWarehouseDO::getType, 2)
                    .eq(GoldMaterialWarehouseDO::getStatus, 1) // 启用状态
                    .orderByAsc(GoldMaterialWarehouseDO::getId);
            return selectList(wrapper);
        }
        return null;
    }
}